package de.gwtprime.server.servlets;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.util.SocialAuthUtil;

import de.gwtprime.server.util.AppUtils;

public class SocialAuthCallbackServlet extends HttpServlet {

	/**
	 * Serial ID
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		if(true)
			throw new IllegalArgumentException("Social media login is disabled!");
		
		response.getWriter().println("callback2");
		HttpSession session = request.getSession();
		
		// get the auth provider manager from session
		  SocialAuthManager manager = (SocialAuthManager)session.getAttribute("authManager");
		  response.getWriter().println("got manager: "+manager+"<br>");
		  // call connect method of manager which returns the provider object. 
		  // Pass request parameter map while calling connect method.
		   Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request); 
		   
		   response.getWriter().println("<br>map:<br>"+paramsMap);
		   AuthProvider provider;
		try {
			provider = manager.connect(paramsMap);
			 response.getWriter().println("got manage2r<br>");

		  // get profile
		  Profile p = provider.getUserProfile();
		  
		  response.getWriter().println("profile: "+p);

		  // you can obtain profile information
		  response.getWriter().println(p.getFirstName());
		  response.getWriter().println("--->"+p);
		  
		  
		  // set the email to session
		  request.getSession().setAttribute("userName", p.getEmail());
		  
		  // redirect to application
		  response.sendRedirect(AppUtils.getApplitionURL(request)+request.getSession().getAttribute("lastPage"));
		} catch (Exception e) {
			 response.getWriter().println("<br><br>---------------------------------<br>"+e+"<br><br>---------------------------------<br>");
			
			 response.getWriter().println("<br><br>---------------------------------<br>"+e.getMessage()+"<br><br>---------------------------------<br>");
			 response.getWriter().println("<br><br>---------------------------------<br>"+e.getStackTrace()+"<br><br>---------------------------------<br>");
			 e.printStackTrace();
		}
	}
}
